package day06.concurrent03;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Lock的优势3：可以有多个Condition进行更精细的线程间通信控制
 * 经典面试题，启动三个线程1 2 3，要求三个线程按照1 2 3的顺序执行
 */
public class Demo07 {
    private static Lock lock = new ReentrantLock();
    private static Condition cond2 = lock.newCondition();
    private static Condition cond3 = lock.newCondition();

    public static void main(String[] args) {
       new Thread(new Runnable() {
            @Override
            public void run() {
                //try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
                try {
                    lock.lock();
                    cond3.await();
                    System.out.print("3");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                //try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
                try {
                    lock.lock();
                    cond2.await();
                    System.out.print("2");
                    cond3.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                //try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
                lock.lock();
                System.out.print("1");
                cond2.signal();
                lock.unlock();
            }
        }).start();
    }
}
